import {Http, storage} from '@/utils'
import {Toast} from 'antd-mobile'
import {history} from 'umi'

export default {
  state: {
    token: storage.get('token'),
    user: storage.get('user'),
    menus: storage.get('menus')
  },
  reducers: {
    setUser(state, payload) {
      return {
        ...state,
        ...payload
      }
    }
  },
  effects: {
    async setUserAsync(dispatch, rootState, payload) {
      dispatch({
        type: 'setUser',
        payload
      })
    },
    async loginAsync(dispatch, rootState, payload) {
      const result = await Http({
        url: '/user/login',
        body: payload
      })
      if (result) {
        const {token, user, menus} = result
        storage.set('token', token)
        storage.set('user', user)
        storage.set('menus', menus)
        dispatch({
          type: 'setUser',
          payload: result
        })
        if (!menus || !menus.length || !menus[0].children || !menus[0].children.length) {
          Toast.fail('你没有权限进入')
        }else {
          Toast.success('登录成功')
          setTimeout(() => {
            window.location.href = menus[0].url
          }, 200)
        }
      }
    },
    async registerAsync(dispatch, rootState, payload) {
      const result = await Http({
        url: '/user',
        body: payload
      })
      if (result) {
        Toast.success('注册成功')
        history.push('/login')
      }
    },
    async logoutAsync(dispatch, rootState, payload) {
      await Http({
        url: '/user/logout',
        body: payload
      })
      Toast.success('退出成功')
      storage.clear()
      window.location.href = '/login'
    }
  }
}
